/**
 * 配置管理控制
 */
package com.p2p.backend.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.p2p.backend.service.OplogService;
import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.model.Action;
import com.p2p.base.model.Module;
import com.p2p.base.model.Oplog;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.SysConfig;
import com.p2p.front.service.SysConfigService;

/**
 * @author ruiqi
 *
 */
@RequestMapping("/sysConfig")
@Controller
public class SysConfigController extends BaseController{

	@Resource
	private SysConfigService sysConfigService;
	
	@PermissionNeed("sys_config_view")
	@RequestMapping("/showAllConfig")
	public void showAllConfig(HttpServletResponse response){
		List<SysConfig> list = sysConfigService.queryAll();
		Map<String,Object> data = new HashMap<String,Object>();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("res", 1);
		jsonObject.put("data", data);
		
		data.put("rows", list);
		data.put("total", list.size());
		this.returnJsonObject(response, jsonObject);
		
	}
	
	@PermissionNeed("sys_config_management")
	@RequestMapping("/getByKey")
	public void getByKey(HttpServletResponse response,String syskey){
		JSONObject jsonObject = new JSONObject();
		SysConfig.ConfigKeyEnum configKeyEnum =SysConfig.ConfigKeyEnum.getByName(syskey);
		if(configKeyEnum==null){
			jsonObject.put("res", 0);
		}
		
		SysConfig sysConfig = sysConfigService.getByKey(configKeyEnum);
		
		jsonObject.put("res", 1);
		Map<String,Object> data = new HashMap<String,Object>();
		jsonObject.put("data", data);
		
		data.put("syskey", sysConfig.getSyskey());
		data.put("value", sysConfig.getValue());
		data.put("memo", sysConfig.getMemo());
		this.returnJsonObject(response, jsonObject);
		
	}
	
	@PermissionNeed("sys_config_management")
	@RequestMapping("/saveByKey")
	public void saveByKey(HttpServletResponse response,SysConfig sysConfig, HttpServletRequest request){
		JSONObject jsonObject = new JSONObject();
		SysConfig.ConfigKeyEnum configKeyEnum =SysConfig.ConfigKeyEnum.getByName(sysConfig.getSyskey());
		if(configKeyEnum==null){
			jsonObject.put("res", 0);
			returnJsonObject(response, jsonObject);
			return;
		}
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.SYS_CONFIG);
		oplog.setAction(Action.UPDATE);
		oplog.setParams(ToStringBuilder.reflectionToString(sysConfig));
		OplogService.log(oplog);
		sysConfigService.save(sysConfig);
		jsonObject.put("res", 1);
		
		this.returnJsonObject(response, jsonObject);
		
	}
}
